package com.sportmall.common;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

public class TokenCache {
    private static Logger logger = LoggerFactory.getLogger(TokenCache.class);

    public static final String TOKEN_PREFIX = "token_";
    //缓存有效时间
    private static int duration = 12;

    private static LoadingCache<String, String> localCache = CacheBuilder.newBuilder()
            .initialCapacity(1000)  //初始容量
            .maximumSize(10000)
            .expireAfterAccess(duration, TimeUnit.HOURS)
            .build(new CacheLoader<String, String>() {
                @Override
                public String load(String key) throws Exception {
                    return null;
                }
            });

    /**
     * 设置token缓存
     * @param key
     * @param value
     */
    public static void setKey(String key, String value) {
        localCache.put(TOKEN_PREFIX + key, value);
    }

    /**
     * 读取token缓存
     * @param key
     * @return
     */
    public static String getKey(String key) {
        String value = null;
        try {
            localCache.get(TOKEN_PREFIX + key);
        } catch (ExecutionException e) {
            logger.error("localcache get error");
        }
        return value;
    }
}
